<template>
  <base-breadcrumb :title="$route.meta.title">
    <a-card :bordered="false">
      <a-tabs default-active-key="1" :activeKey="activeKey" @change="callback">
        <a-tab-pane v-for="(item, index) in tabs" :key="item.value" :tab="item.label">
          <searchData class="noshadow" :show-title-name="false" :search-data="item.searchData" @search="search" />

          <div v-if="item.value==='1'" class="table-operator">
            <a-button v-btnPermission="[{code:'seex_pm_054_add_05',ident:'prma_seex'},{code:'buco_pm_054_add_05',ident:'prma_buco'}]" type="primary" @click="handleOperation('add')">新增考核</a-button>
          </div>
          <div v-if="item.value==='2'" class="table-operator">
            <a-button v-btnPermission="[{code:'seex_pm_054_add_09',ident:'prma_seex'},{code:'buco_pm_054_add_09',ident:'prma_buco'}]" type="primary" @click="handleOperation('add')">新增考核</a-button>
          </div>
          <list-table
            :defaultLoad="true"
            :ref="`table${item.value}`"
            :page-keys="['pageNum', 'pageSize','total']"
            size="default"
            rowKey="id"
            :columns="item.columns"
            :request="item.loadData"
            show-pagination="auto"
          >
            <span slot="serial" slot-scope="text, record, index">{{ index + 1 }}</span>
            <template slot="state" slot-scope="text, record, index">
              <span :style="text == '3' ? { color: '#ff0000' } : {}">
                {{stateName(text)}}
                <span style="color:#FF0000" v-if="dateCalculation(record)">（超期）</span> 
              </span>
            </template>

            <template slot="action" slot-scope="text, record">
              <MoreButton>
              <!-- 自查按钮 -->
              <template v-if="activeKey == '0'">
                <span v-if="record.state!=='3'" v-btnPermission="[{code:'seex_pm_054_loo_01',ident:'prma_seex'},{code:'buco_pm_054_loo_01',ident:'prma_buco'}]">
                  <a @click="handleOperation('look', record)">查看</a>
                </span>

                <span v-if="record.state === '0' || record.state === '4'" v-btnPermission="[{code:'seex_pm_054_edi_02',ident:'prma_seex'},{code:'buco_pm_054_edi_02',ident:'prma_buco'}]">
                  <a @click="handleOperation('edit', record)">编辑</a>
                </span>

                <template v-if="record.state == '2' || record.state == '4' || record.state == '5'">
                  <approval-button :id="record.id" text="审批信息" />
                </template>

                <template v-if="
                  ((record.state === '1' || record.state === '5') && record.problem == '0')
                  || (record.state === '5' && record.problem == '1' && record.completeEffect == '已完成')"
                >
                  <!-- 已提交且无问题的、审批通过有问题且完成效果已填写的，可导出 -->
                  <ExportMould
                    v-btnPermission="[{code:'seex_pm_054_exp_03',ident:'prma_seex'},{code:'buco_pm_054_exp_03',ident:'prma_buco'}]"
                    :servicei-url="exportConfig.server"
                    :url="exportConfig.url"
                    :is-button="false"
                    :request-params="{id: record.id}"
                  />
                </template>
              </template>
              <!-- 分公司抽查按钮 -->
              <template v-else-if="activeKey == '1'">
                <span v-btnPermission="[{code:'seex_pm_054_loo_04',ident:'prma_seex'},{code:'buco_pm_054_loo_04',ident:'prma_buco'}]">
                  <a @click="handleOperation('look', record)">查看</a>
                </span>

                <template v-if="(record.state === '0' || record.state === '4') && (isSelf(record) || record.createType==2)">
                  <span v-btnPermission="[{code:'seex_pm_054_edi_07',ident:'prma_seex'},{code:'buco_pm_054_edi_07',ident:'prma_buco'}]">
                    <a @click="handleOperation('edit', record)">编辑</a>
                  </span>
                </template>

                <template v-if="(record.state === '0') && (isSelf(record) || record.createType==2) && hideBuquBtn()">
                  <a @click="handleOperation('del', record)">删除</a>
                </template>

                <template v-if="record.state == '2' || record.state == '4' || record.state == '5'">
                  <approval-button :id="record.id" text="审批信息" />
                  <!-- <a>审批信息</a> -->
                </template>
                <!-- 审批通过且无问题的、审批通过有问题且完成效果已填写的，可导出 -->
                <template v-if="record.state === '5'">
                  <ExportMould
                    v-if="record.problem=='0' || (record.problem == '1' && record.completeEffect == '已完成')"
                    v-btnPermission="[{code:'seex_pm_054_exp_06',ident:'prma_seex'},{code:'buco_pm_054_exp_06',ident:'prma_buco'}]"
                    :servicei-url="exportConfig.server"
                    :url="exportConfig.url"
                    :is-button="false"
                    :request-params="{id: record.id}"
                  />
                </template>
              </template>
              <!-- 抽查按钮 -->
              <template v-else-if="activeKey == '2'">
                <span v-btnPermission="[{code:'seex_pm_054_loo_08',ident:'prma_seex'},{code:'buco_pm_054_loo_08',ident:'prma_buco'}]">
                  <a @click="handleOperation('look', record)">查看</a>
                </span>

                <template v-if="(record.state === '0' || record.state === '4') && (isSelf(record) || record.createType==2)">
                  <span v-btnPermission="[{code:'seex_pm_054_edi_07',ident:'prma_seex'},{code:'buco_pm_054_edi_07',ident:'prma_buco'}]">
                    <a @click="handleOperation('edit', record)">编辑</a>
                  </span>
                </template>

                <template v-if="(record.state === '0') && (isSelf(record) || record.createType==2) && hideBuquBtn()">
                  <a @click="handleOperation('del', record)">删除</a>
                </template>

                <template v-if="record.state == '2' || record.state == '4' || record.state == '5'">
                  <approval-button :id="record.id" text="审批信息" />
                  <!-- <a>审批信息</a> -->
                </template>
                <!-- 审批通过且无问题的、审批通过有问题且完成效果已填写的，可导出 -->
                <template v-if="record.state === '5'">
                  <ExportMould
                    v-if="record.problem=='0' || (record.problem == '1' && record.completeEffect == '已完成')"
                    v-btnPermission="[{code:'seex_pm_054_exp_11',ident:'prma_seex'},{code:'buco_pm_054_exp_11',ident:'prma_buco'}]"
                    :servicei-url="exportConfig.server"
                    :url="exportConfig.url"
                    :is-button="false"
                    :request-params="{id: record.id}"
                  />
                </template>
              </template>
              </MoreButton>
            </template>
          </list-table>
        </a-tab-pane>
      </a-tabs>
    </a-card>
  </base-breadcrumb>
</template>

<script>

import { statusList2, searchOption1, searchOption2, searchOption3, columns1, columns2 } from './model.js'
import { getPlanExamineList, deletePlanExamine, getPlanExamineExcel } from '@/api/project/projectPlanningAssessment'
import ExportMould from '@/components/ServiceExportMould'
export default {
  name: 'ProjectRecord',
  components: {
    ExportMould
  },
  data() {
    return {
      statusList2,
      searchOption1,
      columns1,
      searchOption2,
      columns2,
      searchOption3,
      activeKey: '0',
      exportConfig: getPlanExamineExcel(),

      queryParam0: {},
      queryParam1: {},
      queryParam2: {},
      loadData0: (parameter) => {
        let param = {
          type: '0',
          isDelete: '0',
          ...this.queryParam0
        }
        const requestParameters = Object.assign({}, parameter, { param: param })
        return getPlanExamineList(requestParameters).then((res) => {
          return {code: 200, data: res.data.list, ...res.data }
        }).catch((err) => {
          return {
            code: 500,
            err
          }
        })
      },
      loadData1: (parameter) => {
        let param = {
          type: '1',
          isDelete: '0',
          companyType: '1',
          ...this.queryParam1
        }
        // if(param.examineYearMonthStart || param.examineYearMonthEnd){
        //   param.examineTimeStart = param.examineYearMonthStart
        //   param.examineTimeEnd = param.examineYearMonthEnd
        //   delete param.examineYearMonthStart
        //   delete param.examineYearMonthEnd
        // }
        const requestParameters = Object.assign({}, parameter, { param:param })
        return getPlanExamineList(requestParameters).then((res) => {
          return {code: 200, data: res.data.list, ...res.data }
        }).catch((err) => {
          return {
            code: 500,
            err
          }
        })
      },
      loadData2: (parameter) => {
        let param = {
          type: '1',
          isDelete: '0',
          companyType: '2',
          ...this.queryParam2
        }
        console.log(param,11111111)
        const requestParameters = Object.assign({}, parameter, { param:param })
        return getPlanExamineList(requestParameters).then((res) => {
          return {code: 200, data: res.data.list, ...res.data }
        }).catch((err) => {
          return {
            code: 500,
            err
          }
        })
      },
    }
  },
  computed: {
    dateCalculation() {
      return (row) => {
        if(row.state != '0' || this.activeKey == '2') {
          return false
        }
        var date = new Date()
        var year = date.getFullYear()
        var month = date.getMonth() + 1
        var strDate = date.getDate()
        if(!row.examineYear || !row.examineMonth) return false
        var datayear = row.examineYear
        var datamonth = row.examineMonth.replace(datayear, '')
        if(datamonth.startsWith('0')) datamonth = datamonth.replace('0', '')
        console.log(datayear, datamonth)
        if(year > datayear) return true;
        if(year == datayear && month > datamonth) return true
        if(this.activeKey == '0') {
          if(strDate > 26) return true
        }    
        return false;
      }
    },
    stateName() {
      return (val) => {
        return this.statusList2.find((v) => v.value == val)?.label
      }
    },
    isSelf() {
      return (val) => {
        return val.examineUserId == this.$userInfo()?.employee?.userId
      }
    },
    currentPost() {
      return this.$currentPost()
    },
    tabs() {
      let list = [
        {
          label: '项目部自查',
          value: '0',
          searchData: this.searchOption1.map((v, i) => {
            if (i == 0) {
              v.autoSelected = this.currentPost.code !== 'CO'
            }
            if (i == 1) {
              v.autoSelected = this.currentPost.code == 'PD'
              console.log(v)
            }
            return v
          }),
          columns: columns1,
          loadData: this.loadData0
        },
        {
          label: '分公司检查',
          value: '1',
          searchData: this.searchOption2.map((v, i) => {
            if (i == 0) {
              v.autoSelected = this.currentPost.code !== 'CO'
            }
            if (i == 1) {
              v.autoSelected = this.currentPost.code == 'PD'
            }
            return v
          }),
          columns: columns2,
          loadData: this.loadData1
        },
        {
          label: '公司检查',
          value: '2',
          searchData: this.searchOption3.map((v, i) => {
            if (i == 0) {
              v.autoSelected = this.currentPost.code !== 'CO'
            }
            if (i == 1) {
              v.autoSelected = this.currentPost.code == 'PD'
            }
            return v
          }),
          columns: columns2,
          loadData: this.loadData2
        }
      ]
      return list
    }
  },
  beforeRouteEnter(to, from, next) {
    if (from.query.activeKey == '1') {
      next((vm) => {
        vm.activeKey = '1'
      })
    } else {
      next()
    }
  },
  created() {
    
  },
  methods: {
    search(e) {
      let param = this.$clone(e)
      if (param.examineYearMonthStart && param.examineYearMonthEnd) {
        param.examineYearMonthStart = param.examineYearMonthStart.replace('-', '')
        param.examineYearMonthEnd = param.examineYearMonthEnd.replace('-', '')
      }
      if (param.grade) {
        param.gradeStart = param.grade.split(',')[0]
        param.gradeEnd = param.grade.split(',')[1]
        delete param.grade
      }
      if (this.activeKey == '0') {
        this.queryParam0 = {
          ...param
        }
      } else if (this.activeKey == '1') {
        this.queryParam1 = {
          ...param
        }
      } else if (this.activeKey == '2') {
        this.queryParam2 = {
          ...param
        }
      }
      this.$refs[`table${this.activeKey}`] && this.$refs[`table${this.activeKey}`][0].refresh(true)
    },
    callback(e) {
      this.activeKey = e;
    },
    handleOperation(type, record = {}) {
      if (type == 'del') {
        this.delete(record)
        return
      }
      let obj = {
        path: '/project/projectPlanningAssessment/assessment/edit',
        query: {
          activeKey: this.activeKey,
          type,
        }
      }
      let { id } = record;
      if (id) {
        obj.query.id = id
      }
      this.$router.push(obj)
    },
    delete(e) {
      let that = this
      that.$confirm({
          title: '温馨提示',
          content: '确定是否删除数据？',
          okText: '确认',
          okType: 'danger',
          cancelText: '取消',
          onOk() {
            return deletePlanExamine(e.id).then((res) => {
                  that.$message.success('删除成功！')
                  that.search()
              }).catch((err) => {
                console.log('err:', err)
                  that.$message.warning('删除失败！')
              })
          },
      })
    },
  }
}
</script>

<style>
  .noshadow .ant-card{
    box-shadow: none
  }
</style>
